import * as React from "react"
import { Link, RouteComponentProps, withRouter } from "react-router-dom"
import style from "./style.less"
import Toast from "../../components/Toast"
import * as api from "../../services/api"

interface State {
  username: string
  password: string
}

class Login extends React.Component<RouteComponentProps> {
  state: State = {
    username: '',
    password: '',
  }  

  async login(){
    try{
      let result = await api.login(this.state.username, this.state.password)
      if (result.stat === 'OK') {
        this.props.history.push('/mine')
      } else {
        Toast.show(result.message)
      }
    } catch {}
  }

  isDisabled() {
    let disabled = false
    if (this.state.username !== '' && this.state.password !== '') {
      disabled = true
    } else {
      disabled = false
    }
    if (disabled) {
      return (
        <button className={style.button} onClick={this.login.bind(this)} >
          登 录
        </button>
      )
    } else {
      return (
        <button className={style.button} disabled onClick={this.login.bind(this)} >
          登 录
        </button>
      )
    }
  }

  render() {
    return (
      <div className={style.wrap}>
        <Link to="/product" className={style.tao}>
          <img src="https://gw.alicdn.com/tfs/TB1puqzr6MZ7e4jSZFOXXX7epXa-160-160.png" className={style.img}/>
        </Link>
        <input
          type="text"
          placeholder="用户名"
          className={style.inputText}
          onChange={event => this.setState({username: event.target.value})}
        />
        <input 
        type="password" 
        placeholder="密 码" 
        className={style.inputText}
        onChange={event => this.setState({password: event.target.value})}
        />
        {this.isDisabled()}
      </div>
    );
  }
}

export default withRouter(Login)
